<template>
  <div >
    <div style="margin: 10px 0">
      <div v-role="'超级管理员'" style="margin-bottom: 10px;display: inline-block">
        <el-radio-group v-model="lookMe" @input="page">
          <el-radio :label=true>只看我自己</el-radio>
          <el-radio :label=false>查看所有报表</el-radio>
        </el-radio-group>
      </div>

      <div>
        <span class="conditionLabel">任务状态 : </span>
        <el-radio-group v-model="taskStatus" @input="page">
          <el-radio-button :label=-1>所有</el-radio-button>
          <el-radio-button :label=0>未开始</el-radio-button>
          <el-radio-button :label=1>执行中</el-radio-button>
          <el-radio-button :label=2>已结束</el-radio-button>
          <el-radio-button :label=3>已失败</el-radio-button>
        </el-radio-group>

        <div style="margin-left: 20px;display: inline-block">
          <span class="conditionLabel">时间范围 : </span>
          <el-date-picker
              style="width: 80%"
              v-model="dateScope"
              type="datetimerange"
              align="right"
              unlink-panels
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd HH:mm:ss"
              value-format="yyyy-MM-dd HH:mm:ss"
              @change="page"
          >
          </el-date-picker>
        </div>
      </div>

      <div style="margin-top: 10px">
        <span class="conditionLabel">搜索 : </span>
        <el-input type="number" class="searchInput" v-model="searchFiled.statementId" placeholder="模板编号(精确)"
                  :clearable=true></el-input>
        <el-input type="number" class="searchInput" v-model="searchFiled.adId" placeholder="发起者编号(精确)"
                  :clearable=true></el-input>
        <el-input type="number" class="searchInput" v-model="searchFiled.taskId" placeholder="任务编号(精确)"
                  :clearable=true></el-input>
        <el-input type="number" class="searchInput" v-model="searchFiled.taskTemplateId" placeholder="任务模板编号(精确)"
                  :clearable=true></el-input>
        <el-input class="searchInput" v-model="searchFiled.taskName" placeholder="任务名称(模糊)" :clearable=true></el-input>
        <el-input type="number" class="searchInput" v-model="searchFiled.robotNumber" placeholder="机器编号(精确)"
                  :clearable=true></el-input>
        <el-button type="primary" @click="search()">搜索</el-button>
        <el-button type="info" @click="clearableSearchInput()">清空</el-button>
      </div>


      <div style="margin:10px 0" v-permission="'robot.taskStatement.delete'">
        <el-popconfirm
            title="这是一段内容确定删除吗？"
            @confirm="remove()"
        >
          <el-button slot="reference" type="danger" plain>删除所有选中项</el-button>
        </el-popconfirm>
      </div>


    </div>
    <!-- 表格,分页 栏 -->
    <div style="margin-top: 10px">
      <el-table
          :height="'60vh'"
          :v-loading="table.tbLoading"
          :data="table.data"
          :stripe=true
          :border=true
          style="width: 100%;"
          @selection-change="table.sRowChange"
      >
        <el-table-column
            type="selection"
            width="55"
            fixed="left"
        >
        </el-table-column>

        <el-table-column
            prop="taskName"
            label="任务名称"
            width="200"
            fixed="left"
        >
        </el-table-column>

        <el-table-column
            prop="adId"
            label="发起者编号"
            width="100"
        >
        </el-table-column>

        <el-table-column
            prop="taskTemplateId"
            label="任务模板编号"
            width="200"
        >
        </el-table-column>

        <el-table-column
            prop="taskId"
            label="任务编号"
            width="100"
        >
        </el-table-column>

        <el-table-column
            prop="robotNumber"
            label="机器编号"
            width="200"
        >
        </el-table-column>

        <el-table-column
            prop="robotIp"
            label="机器IP"
            width="150"
        >
        </el-table-column>

        <el-table-column
            prop="createTime"
            label="创建时间"
            width="180"
        >
        </el-table-column>

        <el-table-column
            prop="taskTemplateName"
            label="任务模板名称"
            width="200"
            fixed="right"
        >
        </el-table-column>

        <el-table-column
            prop="taskStatus"
            label="任务状态"
            fixed="right"
            width="100"
        >
          <template slot-scope="scope">
            <div>
              <div v-if="isNull(scope.row.errMsg)">
                <div v-html="taskStateToText(scope.row.taskStatus)"></div>
              </div>
              <div v-else>
                <el-tooltip effect="dark" :content="scope.row.errMsg" placement="top-start">
                  <div v-html="taskStateToText(scope.row.taskStatus)"></div>
                </el-tooltip>
              </div>
            </div>
          </template>
        </el-table-column>

        <el-table-column align="center" fixed="right" width="180" label="操作">
          <template slot-scope="scope">
            <div style="display: inline-block;margin-right: 10px"
                 v-permission="'robot.taskStatement.dwFile'">
              <el-tooltip effect="dark" content="下载报表附件" placement="top-start">
                <em
                    v-if="!isNull(scope.row.taskFileSuffix)"
                    class="el-icon-s-claim"
                    style="font-size: 25px;color: #2ed573"
                    @click="dwFile(scope.row.id,scope.row.taskFileSuffix)"
                >
                </em>
              </el-tooltip>
            </div>

            <div style="display: inline-block;margin-right: 10px"
                 v-permission="'robot.taskStatement.dwLog'">
              <el-tooltip effect="dark" content="下载日志文件" placement="top-start">
                <em
                    class="el-icon-notebook-1"
                    style="font-size: 25px;color: #b2bec3"
                    @click="dwLog(scope.row.id)"
                >
                </em>
              </el-tooltip>
            </div>

            <div style="display: inline-block;margin-right: 10px"
                 v-permission="'robot.taskStatement.delete'">
              <el-popconfirm
                  title="这是一段内容确定删除吗？"
                  @confirm="remove(scope.row.id)"
              >
                <em
                    slot="reference"
                    class="el-icon-delete"
                    style="font-size: 25px;color: #ff4757"
                >
                </em>
              </el-popconfirm>

            </div>
          </template>
        </el-table-column>
      </el-table>

      <div style="text-align: center;margin-top: 20px">
        <el-pagination
            background
            :page-size="table.pageSize"
            layout='prev, pager, next, jumper,->, total'
            :total="table.total"
            :page-count="table.pages"
            :current-page="table.pageNo"
            @current-change="table.pageChange"
        >
        </el-pagination>
      </div>
    </div>
  </div>
</template>

<script>
import {isNull} from "@/utils/service"
import RichText from "@/components/utils/RichText"

export default {
  name: "taskStatement",
  components: {
    RichText,
  },
  created() {
    this.page();
  },

  data() {
    let _vm = this;
    return {
      lookMe: true,
      taskStatus: -1,
      dateScope: [],
      searchFiled: {
        statementId: '',
        adId: '',
        taskId: '',
        taskTemplateId: '',
        robotNumber: '',
        taskName: '',
      },
      table: {
        tbLoading: false,
        /* 选中行数据 */
        sRows: [],
        data: [],
        pageNo: 1,
        pages: 0,
        pageSize: 10,
        pageCount: 0,
        pageChange(pageNo) {
          if (pageNo === _vm.table.pageNo) {
            return;
          }
          _vm.table.pageNo = pageNo;
          _vm.page();
        },
        updateStatus(id, status) {
          _vm.$request.post({
            url: 'superAdmin/role/updateStatus',
            params: {
              roleId: id,
              status: status,
            },
            success: res => {
              _vm.$message.success("修改状态成功")
            },
            finally: res => {
              _vm.page();
            }
          })
        },
        sRowChange(rows) {
          _vm.table.sRows = rows;
        }
      },
    }
  },
  methods: {
    isNull: isNull,
    dwFile(statementId, taskFileSuffix) {
      let _t = this;
      const loading = this.$loading({
        lock: true,
        text: '获取文件中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$request.post({
        url: 'robot/statement/dwFile',
        params: {statementId: statementId},
        responseType: 'blob',
        then: res => {
          if (res.status !== 200) {
            _t.$message.error("请求任务附件失败")
            return;
          }
          _t.$download.download0(res.data, "任务报表." + taskFileSuffix, "application/octet-stream")
        },
        finally: res => {
          loading.close()
        }
      })
    },
    dwLog(statementId) {
      let _t = this;
      const loading = this.$loading({
        lock: true,
        text: '获取日志中',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      });
      this.$request.post({
        url: 'robot/statement/dwLog',
        params: {statementId: statementId},
        responseType: 'blob',
        then: res => {
          if (res.status !== 200) {
            _t.$message.error("请求任务日志失败")
            return;
          }
          _t.$download.download0(res.data, "日志.log", "application/octet-stream")
        },
        finally: res => {
          loading.close()
        }
      })
    },
    page() {
      let _t = this;
      let startTime = null;
      let endTime = null;
      if (!isNull(_t.dateScope)) {
        [startTime, endTime] = _t.dateScope
      }
      _t.table.tbLoading = true;
      this.$request.post({
        url: 'robot/statement/page',
        params: {
          pageNo: _t.table.pageNo,
          pageSize: _t.table.pageSize,
          lookMe: _t.lookMe,
          taskStatus: _t.taskStatus,
          startTime: startTime,
          endTime: endTime,
          timeScreen: 'create_time',
          ..._t.searchFiled
        },
        success: res => {
          _t.table.data = res.list
          _t.table.pageNo = res.pageNo
          _t.table.pageCount = res.total
          _t.table.pageSize = res.pageSize
          _t.table.pages = res.pages
        },
        error: (res) => {
          console.log(res);
        },
        finally: res => {
          _t.table.tbLoading = false;
        }
      })
    },
    remove(id) {
      let _t = this;
      let statementIds = [];
      if (id) {
        statementIds.push(id);
      } else {
        if (!isNull(_t.table.sRows)) {
          statementIds = _t.table.sRows.map(row => row.id)
        } else {
          _t.$message.warning("请至少选择一项报表删除")
          return;
        }
      }
      this.$request.post({
        url: 'robot/statement/delete',
        params: {
          statementIds: JSON.stringify(statementIds)
        },
        success: res => {
          _t.$message.success("删除成功")
          _t.page()
        },
      })
    },
    taskStateToText(taskStatus) {
      // 定义字体css
      let fontCss = "font-size: 16px;font-weight: bold;"
      // 定义状态文本和样式
      let statusTexts = {
        0: '未开始',
        1: '执行中',
        2: '已结束',
        3: '已失败',
      }
      // 定义状态样式
      let statusStyles = {
        0: 'color: #747d8c;' + fontCss,
        1: 'color: #70a1ff;' + fontCss,
        2: 'color: #2ed573;' + fontCss,
        3: 'color: #ff4757;' + fontCss,
      }
      // 获取状态文本和样式
      let statusText = statusTexts[taskStatus] || '未知状态'
      let statusStyle = statusStyles[taskStatus] || 'color: #ffa502;' + fontCss
      // 使用模板字符串创建富文本内容
      return `<span style="${statusStyle}">${statusText}</span>`
    },

    clearableSearchInput() {
      let isRefresh = false;
      for (const key in this.searchFiled) {
        if (this.searchFiled.hasOwnProperty(key)) { // 过滤继承属性
          if (!isNull(this.searchFiled[key])) {
            isRefresh = true
          }
          this.searchFiled[key] = ''
        }
      }
      if (isRefresh) {
        this.page();
      }
    },
    search() {
      let isNotEmpty = false;
      for (const key in this.searchFiled) {
        if (this.searchFiled.hasOwnProperty(key) && !isNull(this.searchFiled[key])) { // 过滤继承属性
          isNotEmpty = true;
          break;
        }
      }
      if (isNotEmpty) {
        this.page()
      }
    }
  }
}
</script>

<style scoped>
.conditionLabel {
  font-size: 15px;
  color: #606266;
  font-weight: bold;
}

.searchInput {
  margin: 0 5px;
  width: 13%;
}
</style>